import { TYPES } from './local-storage';
import { Utils } from 'web-module-shared';

export class SessionStorage {

    static setItem(key, value) {
        if (Utils.isNotEmpty(key)) {
            const obj = { value: value, type: TYPES.OTHER };
            if (Utils.isObject(value)) {
                obj.type = TYPES.OBJECT
            } else if (Utils.isNumber(value)) {
                obj.type = TYPES.NUMBER
            } else if (Utils.isString(value)) {
                obj.type = TYPES.STRING
            } else {
                obj.type = TYPES.OTHER
            }
            if (obj.value && obj.value.$resource !== undefined) {
                obj.value = Utils.remove$Prefix(obj.value);
            }
            sessionStorage.setItem(key, JSON.stringify(obj));
        }
    }

    static getItem(key) {
        let value;
        try {
            const obj = JSON.parse(sessionStorage.getItem(key));
            if (obj === TYPES.NUMBER) {
                value = parseInt(obj.value, 10);
            } else {
                value = obj.value;
            }
            return value;
        } catch (error) {
            return sessionStorage.getItem(key);
        }
    }

    static removeItem(key) {
        sessionStorage.removeItem(key);
    }

    static clear() {
        sessionStorage.clear();
    }

}
